"""Initialize AncientSeeker database with sample data.

This script creates initial data including:
- Loading books from JSON files
- Creating admin user (optional)
"""

import sys
import os
from pathlib import Path

# Add the backend directory to Python path
backend_dir = Path(__file__).parent.parent
sys.path.insert(0, str(backend_dir))

import asyncio
from sqlalchemy.orm import Session

from app.database import engine, Base, get_database_session
from app import models  # Import all models to register them
from app.models.user import User
from app.services.book_service import book_service
from app.utils.auth import get_password_hash

# Create all database tables
Base.metadata.create_all(bind=engine)


def create_admin_user(db: Session) -> None:
    """Create default admin user if not exists."""
    admin_user = db.query(User).filter(User.username == "admin").first()
    if not admin_user:
        admin_user = User(
            username="admin",
            password_hash=get_password_hash("admin123"),
            is_admin=True,
            is_guest=False,
            is_active=True,
        )
        db.add(admin_user)
        db.commit()
        print("✓ 管理员用户创建成功 (username: admin, password: admin123)")
    else:
        print("✓ 管理员用户已存在")


def load_initial_books(db: Session) -> None:
    """Load books from JSON files."""
    # 使用绝对路径定位书籍数据目录
    books_dir = backend_dir / "data" / "books"
    summary = book_service.load_books_from_json(db, str(books_dir))
    loaded = summary.get("loaded", 0)
    updated = summary.get("updated", 0)
    skipped = summary.get("skipped", 0)
    errors = summary.get("errors", [])

    if loaded or updated:
        print(
            f"✓ 书籍加载完成: 新增 {loaded} 本, 更新 {updated} 本, 跳过 {skipped} 本, 目录: {summary.get('directory')}"
        )
    else:
        if errors:
            print(
                f"✗ 未能导入书籍，发生 {len(errors)} 个错误 (目录: {summary.get('directory')})"
            )
        else:
            print(
                f"✓ 无需导入，所有 {skipped} 本已存在 (目录: {summary.get('directory')})"
            )


def initialize_database():
    """Initialize database with sample data."""
    print("开始初始化数据库...")

    try:
        # Get database session
        db = next(get_database_session())

        # Create admin user
        create_admin_user(db)

        # Load initial books
        load_initial_books(db)

        print("✓ 数据库初始化完成！")

    except Exception as e:
        print(f"✗ 数据库初始化失败: {e}")
        raise
    finally:
        db.close()


if __name__ == "__main__":
    initialize_database()
